package cn.edu.lingnan.service.impl;

import cn.edu.lingnan.mapper.RoleManageMapper;
import cn.edu.lingnan.mapper.UserMapper;
import cn.edu.lingnan.service.RoleManageService;
import cn.edu.lingnan.user.pojos.Menu;
import cn.edu.lingnan.user.pojos.RoleMenu;
import cn.edu.lingnan.user.vos.UserInfoVo;
import cn.edu.lingnan.utils.JwtUtils;
import cn.edu.lingnan.utils.MD5;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class RoleManageServiceImpl implements RoleManageService {

    @Autowired
    private RoleManageMapper roleManageMapper;

    @Autowired
    private UserMapper userMapper;

    // 查询教师角色的菜单权限
    @Override
    public List<Menu> getMenusByRoleId(int roleId) {
        return roleManageMapper.getMenusByRoleId(roleId);
    }

    // 查询所有菜单
    @Override
    public List<Menu> getAllMenus() {
        return roleManageMapper.getAllMenus();
    }

    // 添加教师角色的菜单权限（包括父菜单检查）
    @Override
    public void addMenuToRoleWithParentCheck(int roleId, int menuId) {
        // 检查菜单是否已关联到角色
        RoleMenu existingRoleMenu = roleManageMapper.getRoleMenu(roleId, menuId);
        if (existingRoleMenu != null) {
            throw new RuntimeException("菜单已关联到角色，无需重复添加");
        }

        // 查询菜单信息
        Menu menu = roleManageMapper.getMenuById(menuId);
        if (menu == null) {
            throw new RuntimeException("菜单不存在");
        }

        // 如果是子菜单，检查父菜单是否已关联到角色
        if (menu.getParentId() != null && menu.getParentId() != 0) {
            // 查询父菜单是否已关联到角色
            RoleMenu parentRoleMenu = roleManageMapper.getRoleMenu(roleId, menu.getParentId());
            if (parentRoleMenu == null) {
                // 如果父菜单未关联到角色，则先关联父菜单
                roleManageMapper.addMenuToRole(roleId, menu.getParentId());
            }
        }

        // 关联当前菜单到角色
        roleManageMapper.addMenuToRole(roleId, menuId);
    }

    // 删除教师角色的菜单权限（递归删除子菜单）
    @Override
    public void removeMenuAndChildrenFromRole(int roleId, int menuId) {
        // 递归获取所有子菜单ID
        List<Integer> menuIdsToDelete = getChildrenMenuIds(menuId);
        menuIdsToDelete.add(menuId); // 包括当前菜单

        // 批量删除
        roleManageMapper.removeMenusFromRole(roleId, menuIdsToDelete);
    }

    // 删除教师角色的菜单权限（递归删除子菜单，带密码验证）
    @Override
    public void removeMenuAndChildrenFromRoleWithPassword(String jwt, int roleId, int menuId, String password) {
        // 从 JWT 中解析 userName
        String userName = getUserNameFromJwt(jwt);

        // 根据 userName 查询用户信息
        UserInfoVo userInfoVo = getUserByUserName(userName);

        // 验证管理员密码
        validateAdminPassword(userInfoVo, password);

        // 递归获取所有子菜单ID
        List<Integer> menuIdsToDelete = getChildrenMenuIds(menuId);
        menuIdsToDelete.add(menuId); // 包括当前菜单

        // 批量删除
        roleManageMapper.removeMenusFromRole(roleId, menuIdsToDelete);
    }

    // 构建菜单树
    @Override
    public List<Menu> buildMenuTree(List<Menu> menus) {
        List<Menu> menuTree = new ArrayList<>();
        for (Menu menu : menus) {
            if (menu.getParentId() == null || menu.getParentId() == 0) {
                // 找到顶级菜单
                menu.setChildren(getChildren(menu.getMenuId(), menus));
                menuTree.add(menu);
            }
        }
        return menuTree;
    }

    // 递归获取所有子菜单ID
    private List<Integer> getChildrenMenuIds(int parentId) {
        List<Integer> menuIds = new ArrayList<>();
        List<Menu> children = roleManageMapper.getChildrenMenus(parentId);
        for (Menu child : children) {
            menuIds.add(child.getMenuId());
            menuIds.addAll(getChildrenMenuIds(child.getMenuId())); // 递归获取子菜单
        }
        return menuIds;
    }

    // 递归获取子菜单
    private List<Menu> getChildren(int parentId, List<Menu> menus) {
        List<Menu> children = new ArrayList<>();
        for (Menu menu : menus) {
            if (parentId == menu.getParentId()) {
                menu.setChildren(getChildren(menu.getMenuId(), menus));
                children.add(menu);
            }
        }
        return children;
    }

    // 从 JWT 中解析 userName
    private String getUserNameFromJwt(String jwt) {
        Map<String, Object> claims = JwtUtils.parseJWT(jwt);
        return (String) claims.get("userName"); // 从 JWT 中获取 userName
    }

    // 根据 userName 查询用户信息
    private UserInfoVo getUserByUserName(String userName) {
        UserInfoVo userInfoVo = userMapper.getUserByUserName(userName);
        if (userInfoVo == null) {
            throw new RuntimeException("用户不存在");
        }
        return userInfoVo;
    }

    // 验证管理员密码
    private void validateAdminPassword(UserInfoVo userInfoVo, String password) {
        // 验证密码
        String salt = userInfoVo.getSalt();
        if (!userInfoVo.getUserPassword().equals(MD5.md5Encrypt(password + salt))) {
            throw new RuntimeException("密码错误");
        }
    }
}